package com.clstu.file;

import org.testng.annotations.Test;

import java.io.FileInputStream;
import java.io.IOException;

public class FileInputStream_ {//字节流

    @Test
     public void readFile01(){
         int readData = 0;//返回字符的ascll码值
         FileInputStream fileInputStream = null;
         try {
             fileInputStream = new FileInputStream("D:\\hello.txt");//字节输入流
             while ((readData = fileInputStream.read()) != -1){//单个字符的读取效率比较低
                 System.out.print((char) readData);//如果有中文就会输出乱码
             }
         } catch (IOException e) {
             e.printStackTrace();
         } finally {
             try {
                 fileInputStream.close();//关闭占用
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
     }

    @Test
    public void readFile02(){
        //int readData = 0;//返回字符的ascll码值
        int readLen = 0;
        byte[]  buf = new byte[8];//假定没次最多读取8个
        FileInputStream fileInputStream = null;//字节输入流
        try {

            fileInputStream = new FileInputStream("D:\\hello.txt");//字节输入流
            while ((readLen=fileInputStream.read(buf)) != -1){//按照多个字符来读取，提升了效率
                                                     //如果读取成功，返回读取的字节数，失败返回-1

                System.out.print(new String(buf,0,readLen));//String 的另一个构造器，开始位置和长度
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();//关闭占用
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
